package com.dragee.modules.work.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragee.common.PageUtils;
import com.dragee.common.R;
import com.dragee.constants.CommonConstants;
import com.dragee.modules.work.dao.ShopCustomerDao;
import com.dragee.modules.work.entity.OrderEntity;
import com.dragee.modules.work.entity.ShopCustomerEntity;
import com.dragee.modules.work.entity.ShopEntity;
import com.dragee.modules.work.service.OrderService;
import com.dragee.modules.work.service.ShopCustomerService;
import com.dragee.modules.work.service.ShopService;
import com.dragee.utils.LoginUserUtil;
import com.dragee.utils.StringUtils;
import com.dragee.utils.WrapperUtil;
import com.dragee.utils.excel.CommonListener;
import com.dragee.utils.excel.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("shopCustomerService")
public class ShopCustomerServiceImpl extends ServiceImpl<ShopCustomerDao, ShopCustomerEntity> implements ShopCustomerService {


    @Resource
    private ShopCustomerDao shopCustomerDao;

    @Autowired
    private ShopService shopService;
    @Autowired
    private OrderService orderService;

    private String business = "shopCustomer";
    /**
    * 列表
    */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        int limit = params.get(CommonConstants.LIMIT) == null
                ?CommonConstants.LIMIT_SIZE:Integer.parseInt(params.get(CommonConstants.LIMIT).toString());
        int start = params.get(CommonConstants.START) == null
                ?CommonConstants.START_SIZE:Integer.parseInt(params.get(CommonConstants.START).toString());
        QueryWrapper<ShopCustomerEntity> wrapper =
                WrapperUtil.getWrapper(business, params, ShopCustomerEntity.class);
        ShopEntity shop = shopService.getShopByUserId(LoginUserUtil.getLoginUserId().toString());
        wrapper.eq("shopId", shop.getId());
        IPage<ShopCustomerEntity> page = new Page<>(start, limit);
        page = baseMapper.selectPage(page, wrapper.select());
        for (ShopCustomerEntity record : page.getRecords()) {
            supplementData(record);
        }
        return new PageUtils(page);
    }


    @Override
    public R importData(MultipartFile file) throws IOException {
        //填充对应词典 sex: (1:男, 2:女)
        Map<String, Map<String,Object>> map = new HashMap<>();
        //解析器
        CommonListener<ShopCustomerEntity> commonListener
                = new CommonListener<>(map, ShopCustomerEntity.class,this::excelBatch);
        EasyExcel.read(file.getInputStream())
                .head(ShopCustomerEntity.class)
                .registerReadListener(commonListener)
                .sheet()
                .doRead();
        List<String> msgList = commonListener.getMsgList();
        if(msgList.size()>0){
            return R.error(StringUtils.join(msgList,","));
        }
        return R.ok();
    }

    @Override
    public void exportData(Map<String, Object> params, HttpServletResponse response) throws Exception {
        QueryWrapper<ShopCustomerEntity> wrapper =
                WrapperUtil.getWrapper(business, params, ShopCustomerEntity.class);
        List<ShopCustomerEntity> datas = list(wrapper);
        ExcelUtils.writeExcel(response,
                datas,
                "顾客" + System.currentTimeMillis(),
                "数据", ShopCustomerEntity.class);
    }

    @Override
    public void supplementData(ShopCustomerEntity customer) {
        List<OrderEntity> orders = orderService.getOrders(customer.getTel(), null);
        BigDecimal totalConsume = new BigDecimal(0);
        for (OrderEntity order : orders) {
            totalConsume = totalConsume.add(new BigDecimal(order.getNeedPay()));
        }
        customer.setTotalConsume(totalConsume.toString());
    }

    /** 导入执行入库方法
     * @param datas
     * @return
     */
    private boolean excelBatch (List<ShopCustomerEntity> datas) {
        for (ShopCustomerEntity data : datas) {
            saveOrUpdate(data);
        }
        return true;
    }

    @Override
    public ShopCustomerEntity getCustomerByTel(String shopId, String tel) {
        return getOne(new QueryWrapper<ShopCustomerEntity>().eq("tel", tel).eq("shopId", shopId), false);
    }

    @Override
    public ShopCustomerEntity getCustomerByOrderId(String orderId) {
        OrderEntity order = orderService.getById(orderId);
        return getCustomerByTel(order.getShopId(), order.getCustomerTel());
    }
}